<?php

class SampleController extends Controller
{
    public $layout='//layouts/column2';

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}
	
	public function actionCreate($id=0)
	{
		$model = new Sample();
		
		if($id != 0)
		{
			$model = Sample::model()->findByPk($id);
		}
		
		if(isset($_POST['User']))
		{
			$data = $_POST['User'];
			
			$model -> setData($data);
			
			if($data['imageUrl'] != "")
			{
				$imgName = Utility::getImageName($data["imageUrl"]);
				$model -> imageUrl = "$imgName";
			}
			 
			if($model -> save())
			{
				if($data["imageUrl"] != "")
				{
					$imageUrl = $data["imageUrl"];
					Utility::saveImage($imageUrl, $imgName, "card");
				}
				
				$this -> redirect(array('list'));
			}
		}
		
		$this->render('create', array(
			'model' => $model
		));
	}
	
	public function actionList()
	{
		$this->render('list');
	}
	
	public function actionSearch()
	{
		$model = new Sample();

		$data = $model -> search();

		echo json_encode(array("results" => $data[0], "total" => $data[1]));
	}
	
	public function actionDelete()
	{
		$data = $_POST['models'][0];
				
		$item = Sample::model() -> findByPk($data['id']);
		
		if ($item -> delete()) {
			echo json_encode(array("status" => 'success'));
		}
		else{
			echo json_encode(array("status" => 'failure'));
		}
	}
	
}